{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "95f0a171",
   "metadata": {},
   "source": [
    "(spreadsheets)=\n",
    "# Spreadsheets\n",
    "\n",
    "## Introduction\n",
    "\n",
    "This chapter will show you how to work with spreadsheets, for example Microsoft Excel files, in Python. We already saw how to import csv (and tsv) files in {ref}`data-import`. In this chapter we will introduce you to tools for working with data in Excel spreadsheets and Google Sheets.\n",
    "\n",
    "If you or your collaborators are using spreadsheets for organising data that will be ingested by an analytical tool like Python, we recommend reading the paper \"Data Organization in Spreadsheets\" by Karl Broman and Kara Woo {cite}`broman2018data`. The best practices presented in this paper will save you much headache down the line when you import the data from a spreadsheet into Python to analyse and visualise. (For spreadsheets that are meant to be read by humans, we recommend the [good practice tables](https://github.com/best-practice-and-impact/gptables) package.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51a55374",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "# remove cell\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib_inline.backend_inline\n",
    "\n",
    "# Plot settings\n",
    "plt.style.use(\"https://github.com/aeturrell/python4DS/raw/main/plot_style.txt\")\n",
    "matplotlib_inline.backend_inline.set_matplotlib_formats(\"svg\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17575f3a",
   "metadata": {},
   "source": [
    "### Prerequisites\n",
    "\n",
    "You will need to install the **pandas** package for this chapter. You will also need to install the **openpyxl** package by running `pip install openpyxl` in the terminal."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff99055a",
   "metadata": {},
   "source": [
    "## Reading Excel (and Similar) Files\n",
    "\n",
    "**pandas** can read in xls, xlsx, xlsm, xlsb, odf, ods, and odt files from your local filesystem or from a URL. It also supports an option to read a single sheet or a list of sheets.\n",
    "\n",
    "To show how this works, we'll work with an example spreadsheet called \"students.xlsx\". The figure below shows what the spreadsheet looks like.\n",
    "\n",
    "![A look at the students spreadsheet in Excel. The spreadsheet contains information on 6 students, their ID, full name, favourite food, meal plan, and age.](https://github.com/hadley/r4ds/raw/main/screenshots/import-spreadsheets-students.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29f2f4e0",
   "metadata": {},
   "source": [
    "The first argument to `pd.read_excel()` is the path to the file to read. If you have downloaded the [file]() onto your computer and put it in a subfolder called \"data\" then you would want to use the path \"data/students.xlsx\" but we can also load it directly from the URL."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf00d4c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "students = pd.read_excel(\n",
    "    \"https://github.com/aeturrell/python4DS/raw/main/data/students.xlsx\"\n",
    ")\n",
    "students"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03d6ba9c",
   "metadata": {},
   "source": [
    "We have six students in the data and five variables on each student. However there are a few things we might want to address in this dataset:\n",
    "\n",
    "- The column names are all over the place. You can provide column names that follow a consistent format; we recommend `snake_case` using the `names` argument.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecce26ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.read_excel(\n",
    "    \"https://github.com/aeturrell/python4DS/raw/main/data/students.xlsx\",\n",
    "    names=[\"student_id\", \"full_name\", \"favourite_food\", \"meal_plan\", \"age\"],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb07ad4f",
   "metadata": {},
   "source": [
    "\n",
    "- `age` is read in as a column of objects, but it really should be numeric. Just like with `read_csv()`, you can supply a `dtype` argument to `read_excel()` and specify the data types for the columns of data you read in. Your options include `\"boolean\"`, `\"int\"`, `\"float\"`, `\"datetime\"`, `\"string\"`, and more. But we can see right away that this isn't going to work with the \"age\" column as it mixes numbers and text: so we first need to map its text to numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22e45cc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "students = pd.read_excel(\n",
    "    \"data/students.xlsx\",\n",
    "    names=[\"student_id\", \"full_name\", \"favourite_food\", \"meal_plan\", \"age\"],\n",
    ")\n",
    "students[\"age\"] = students[\"age\"].replace(\"five\", 5)\n",
    "students"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8a07159",
   "metadata": {},
   "source": [
    "Okay, now we can apply the data types."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f67490d3",
   "metadata": {},
   "outputs": [],
   "source": [
    "students = students.astype(\n",
    "    {\n",
    "        \"student_id\": \"Int64\",\n",
    "        \"full_name\": \"string\",\n",
    "        \"favourite_food\": \"string\",\n",
    "        \"meal_plan\": \"category\",\n",
    "        \"age\": \"Int64\",\n",
    "    }\n",
    ")\n",
    "students.info()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "362ff5a5",
   "metadata": {},
   "source": [
    "It took multiple steps and trial-and-error to load the data in exactly the format we want, and this is not unexpected. Data science is an iterative process. There is no way to know exactly what the data will look like until you load it and take a look at it. The general pattern we used is load the data, take a peek, make adjustments to your code, load it again, and repeat until you're happy with the result."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b00c2a4",
   "metadata": {},
   "source": [
    "### Reading Individual Sheets\n",
    "\n",
    "An important feature that distinguishes spreadsheets from flat files is the notion of multiple sheets. The figure below shows an Excel spreadsheet with multiple sheets. The data come from the **palmerpenguins** dataset {cite}`horst2020palmerpenguins`. Each sheet contains information on penguins from a different island where data were collected.\n",
    "\n",
    "![A look at the penguins spreadsheet in Excel. The spreadsheet contains has three sheets: Torgersen Island, Biscoe Island, and Dream Island.](https://github.com/hadley/r4ds/raw/main/screenshots/import-spreadsheets-penguins-islands.png)\n",
    "\n",
    "You can read a single sheet using the following command (so as not to show the whole file, we'll use `.head()` to just show the first 5 rows):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e37f9e3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.read_excel(\n",
    "    \"https://github.com/aeturrell/python4DS/raw/main/data/penguins.xlsx\",\n",
    "    sheet_name=\"Torgersen Island\",\n",
    ").head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "641f6831",
   "metadata": {},
   "source": [
    "Now this relies on us knowing the names of the sheets in advance. There will be situations where you can to read in data without peeking into the Excel spreadsheet. To read all sheets in, use `sheet_name=None`. The object that's created is a dictionary with key value pairs that are sheet names and data frames respectively. Let's look at the second key value pair (note that we have to convert the keys() and values() objects to list to then retrieve the second element of each using a subscript, ie `list(dictionary.keys())[<element number>]`).\n",
    "\n",
    "To give a sense of how this works, let's first print all of the retrieved keys:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f3a3b78",
   "metadata": {},
   "outputs": [],
   "source": [
    "penguins_dict = pd.read_excel(\n",
    "    \"https://github.com/aeturrell/python4DS/raw/main/data/penguins.xlsx\",\n",
    "    sheet_name=None,\n",
    ")\n",
    "print([x for x in penguins_dict.keys()])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "076f1ebe",
   "metadata": {},
   "source": [
    "Now let's show the second entry data frame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15495426",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(list(penguins_dict.keys())[1])\n",
    "list(penguins_dict.values())[1].head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "536ab4bb",
   "metadata": {},
   "source": [
    "What we really want is these three *consistent* datasets to be in the *same* single data frame. For this, we can use the `pd.concat()` function. This concatenates any given iterable of data frames."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "151ba846",
   "metadata": {},
   "outputs": [],
   "source": [
    "penguins = pd.concat(penguins_dict.values(), axis=0)\n",
    "penguins"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa458187",
   "metadata": {},
   "source": [
    "### Reading Part of a Sheet\n",
    "\n",
    "Since many use Excel spreadsheets for presentation as well as for data storage, it's quite common to find cell entries in a spreadsheet that are not part of the data you want to read in.\n",
    "\n",
    "The figure below shows such a spreadsheet: in the middle of the sheet is what looks like a data frame but there is extraneous text in cells above and below the data.\n",
    "\n",
    "![A look at the deaths spreadsheet in Excel. The spreadsheet has four rows on top that contain non-data information; the text 'For the same of consistency in the data layout, which is really a beautiful thing, I will keep making notes up here.' is spread across cells in these top four rows. Then, there is a data frame that includes information on deaths of 10 famous people, including their names, professions, ages, whether they have kids or not, date of birth and death. At the bottom, there are four more rows of non-data information; the text 'This has been really fun, but we're signing off now!' is spread across cells in these bottom four rows.](https://github.com/hadley/r4ds/raw/main/screenshots/import-spreadsheets-deaths.png)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61505c86",
   "metadata": {},
   "source": [
    "This spreadsheet can be downloaded from [here](https://github.com/aeturrell/python4DS/tree/main/data) or you can load it directly from a URL. If you want to load it from your own computer's disk, you'll need to save it in a sub-folder called \"data\" first.\n",
    "\n",
    "\n",
    "The top three rows and the bottom four rows are not part of the data frame. We could skip the top three rows with `skiprows`. Note that we set `skiprows=4` since the fourth row contains column names, not the data.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29987b9d",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.read_excel(\"data/deaths.xlsx\", skiprows=4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1a8c3ca",
   "metadata": {},
   "source": [
    "We could also set `nrows` to omit the extraneous rows at the bottom (another option would to be to skip a set number of rows at the end using `skipfooter`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d7a3db3",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.read_excel(\"data/deaths.xlsx\", skiprows=4, nrows=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d277c3a",
   "metadata": {},
   "source": [
    "## Data Types\n",
    "\n",
    "In CSV files, all values are strings. This is not particularly true to the data, but it is simple: everything is a string.\n",
    "\n",
    "The underlying data in Excel spreadsheets is more complex. A cell can be one of five things:\n",
    "\n",
    "-   A logical, like TRUE / FALSE\n",
    "\n",
    "-   A number, like \"10\" or \"10.5\"\n",
    "\n",
    "-   A date, which can also include time like \"11/1/21\" or \"11/1/21 3:00 PM\"\n",
    "\n",
    "-   A string, like \"ten\"\n",
    "\n",
    "-   A currency, which allows numeric values in a limited range and four decimal digits of fixed precision\n",
    "\n",
    "When working with spreadsheet data, it's important to keep in mind that how the underlying data is stored can be very different than what you see in the cell. For example, Excel has no notion of an integer. All numbers are stored as floating points (real number), but you can choose to display the data with a customizable number of decimal points. Similarly, dates are actually stored as numbers, specifically the number of seconds since January 1, 1970. You can customize how you display the date by applying formatting in Excel. Confusingly, it's also possible to have something that looks like a number but is actually a string (e.g. type `'10` into a cell in Excel).\n",
    "\n",
    "These differences between how the underlying data are stored vs. how they're displayed can cause surprises when the data are loaded into analytical tools such as **pandas**. By default, **pandas** will guess the data type in a given column.\n",
    "A recommended workflow is to let **pandas** guess the column types initially, inspect them, and then change any data types that you want to."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d73bbad",
   "metadata": {},
   "source": [
    "## Writing to Excel\n",
    "\n",
    "Let's create a small data frame that we can then write out. Note that `item` is a category and `quantity` is an integer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15963e18",
   "metadata": {},
   "outputs": [],
   "source": [
    "bake_sale = pd.DataFrame(\n",
    "    {\"item\": pd.Categorical([\"brownie\", \"cupcake\", \"cookie\"]), \"quantity\": [10, 5, 8]}\n",
    ")\n",
    "bake_sale"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "345bca3d",
   "metadata": {},
   "source": [
    "You can write data back to disk as an Excel file using the `<dataframe>.to_excel()` function. The `index=False` keyword argument just writes the two columns without the index that was automatically added in the last step."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fc17141",
   "metadata": {},
   "source": [
    "```python\n",
    "bake_sale.to_excel(\"data/bake_sale.xlsx\", index=False)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f892c2e7",
   "metadata": {},
   "source": [
    "The figure below shows what the data looks like in Excel.\n",
    "\n",
    "![Bake sale data frame created earlier in Excel.](https://github.com/hadley/r4ds/raw/main/screenshots/import-spreadsheets-bake-sale.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d555c84",
   "metadata": {},
   "source": [
    "Just like reading from a CSV, information on data type is lost when we read the data back in—you can see this is you read the data back in and check the `info` for the data types. Although we kept `int64` because **pandas** recognise that the second column was of integer type, we lost the categorical data type for \"item\". This data type loss makes Excel files unreliable for caching interim results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27e128f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.read_excel(\"data/bake_sale.xlsx\").info()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "215634bf",
   "metadata": {},
   "source": [
    "### Formatted Output\n",
    "\n",
    "If you need more formatting options and more control over how you write spreadsheets, check out the documentation for [openpyxl](https://openpyxl.readthedocs.io/) which can do pretty much everything you imagine. Generally, releasing data in spreadsheets is not the best option: but if you do want to release data in spreadsheets according to best practice, then check out [gptables](https://gptables.readthedocs.io/)."
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "9d7534ecd9fbc7d385378f8400cf4d6cb9c6175408a574f1c99c5269f08771cc"
  },
  "jupytext": {
   "cell_metadata_filter": "-all",
   "encoding": "# -*- coding: utf-8 -*-",
   "formats": "md:myst",
   "main_language": "python"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  },
  "toc-showtags": true
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
